package com.ruoyi.message.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.common.utils.CreateIdUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.file.domain.FileInfo;
import com.ruoyi.file.mapper.FileInfoMapper;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.message.domain.MailFromUser;
import com.ruoyi.message.domain.MailToUser;
import com.ruoyi.message.mapper.MailFromUserMapper;
import com.ruoyi.message.service.IMailFromUserService;
import com.ruoyi.message.service.IMailToUserService;
import com.ruoyi.servie.param.MailAttachment;
import com.ruoyi.servie.param.MailParam;
import com.ruoyi.servie.service.IMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import javax.mail.MessagingException;

/**
 * 邮箱发件人账号Service业务层处理
 * 
 * @author shushuang
 * @date 2019-10-17
 */
@Service
@Slf4j
public class MailFromUserServiceImpl implements IMailFromUserService
{
    @Autowired
    private MailFromUserMapper mailFromUserMapper;

    @Autowired
    private IMailToUserService iMailToUserService;

    @Autowired
    private IMailService iMailService;

    @Autowired
    private FileInfoMapper fileInfoMapper;


    @Value("${ftp.picserver}")
    public String picserver;


    /**
     * 查询邮箱发件人账号
     * 
     * @param uuid 邮箱发件人账号ID
     * @return 邮箱发件人账号
     */
    @Override
    public MailFromUser selectMailFromUserById(String uuid)
    {
        return mailFromUserMapper.selectMailFromUserById(uuid);
    }

    /**
     * 查询邮箱发件人账号列表
     * 
     * @param mailFromUser 邮箱发件人账号
     * @return 邮箱发件人账号
     */
    @Override
    public List<MailFromUser> selectMailFromUserList(MailFromUser mailFromUser)
    {
        return mailFromUserMapper.selectMailFromUserList(mailFromUser);
    }

    /**
     * 新增邮箱发件人账号
     * 
     * @param mailFromUser 邮箱发件人账号
     * @return 结果
     */
    @Override
    public int insertMailFromUser(MailFromUser mailFromUser)
    {
        mailFromUser.setUuid(CreateIdUtils.getGenerateUUID());
        Date nowDate = DateUtils.getNowDate();
        mailFromUser.setUpdateTime(nowDate);
        mailFromUser.setCreateTime(nowDate);
        return mailFromUserMapper.insertMailFromUser(mailFromUser);
    }

    /**
     * 修改邮箱发件人账号
     * 
     * @param mailFromUser 邮箱发件人账号
     * @return 结果
     */
    @Override
    public int updateMailFromUser(MailFromUser mailFromUser)
    {
        mailFromUser.setUpdateTime(DateUtils.getNowDate());
        return mailFromUserMapper.updateMailFromUser(mailFromUser);
    }

    /**
     * 删除邮箱发件人账号对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMailFromUserByIds(String ids)
    {
        return mailFromUserMapper.deleteMailFromUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除邮箱发件人账号信息
     * 
     * @param uuid 邮箱发件人账号ID
     * @return 结果
     */
    public int deleteMailFromUserById(String uuid)
    {
        return mailFromUserMapper.deleteMailFromUserById(uuid);
    }


    @Override
    @Transactional
    public void sendMail(String uuid, String mailTo, String subject, String context, String fileIds) throws MessagingException, FileNotFoundException {

        MailFromUser mailFromUser = mailFromUserMapper.selectMailFromUserById(uuid);
        MailParam mailParam = new MailParam(mailFromUser.getMailHost(),mailFromUser.getMailUsername(),mailFromUser.getMailPassword());
        mailParam.setMailFromUserName(mailFromUser.getMailUsername());
        mailParam.setMailToUserName(mailTo);
        mailParam.setSubject(subject);
        mailParam.setText(context);
        List<String> filePathIds = Stream.of(fileIds.split(",")).collect(Collectors.toList());
        mailParam.setIsHtml(true);
        //发邮件
        List<MailAttachment> mailAttachments = new ArrayList<>();
        MailAttachment mailAttachment;
        for (String filePathId: filePathIds) {
            mailAttachment = new MailAttachment();
            FileInfo fileInfo = fileInfoMapper.selectFileInfoById(Long.valueOf(filePathId));

            mailAttachment.setAttachmentFilename(fileInfo.getOriginalName());
            log.info(picserver + "/" + fileInfo.getRelativePath());
            File file = FileUtils.getFileByNetUrl(picserver + "/" + fileInfo.getRelativePath());
            mailAttachment.setFile(file);
            mailAttachments.add(mailAttachment);
        }
        mailParam.setMailAttachments(mailAttachments);

        iMailService.sendMail(mailParam);

        //根据to和ShiroUtils.getUserId()查询是否存在，如果存在就更新时间，如果不存在就新增
        MailToUser mailToUserByUserIdAndMailUserName = iMailToUserService.findByUserIdAndMailUserName(ShiroUtils.getUserId(), mailTo);
        Date nowDate = DateUtils.getNowDate();
        if(mailToUserByUserIdAndMailUserName == null){
            //将收件人信息保存
            MailToUser mailToUser = new MailToUser();
            mailToUser.setUuid(CreateIdUtils.getGenerateUUID());
            mailToUser.setUserId(ShiroUtils.getUserId());
            mailToUser.setMailUsername(mailTo);
            mailToUser.setCreateTime(nowDate);
            mailToUser.setUpdateTime(nowDate);
            iMailToUserService.insertMailToUser(mailToUser);
        }else{
            mailToUserByUserIdAndMailUserName.setUpdateTime(nowDate);
            iMailToUserService.updateMailToUser(mailToUserByUserIdAndMailUserName);
        }
    }
}
